﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Treely.Data.Model.Abstract;
using Treely.DataAccess;

namespace Treely.Data.Repositories
{
    public class MathAnswerableRepository : Repository, IRepository<MathAnswerable>
    {
        public IEnumerable<MathAnswerable> Get()
        {
            return Context.MathAnswerables.AsEnumerable();
        }

        public MathAnswerable Get(int id)
        {
            return Context.MathAnswerables.FirstOrDefault(x => x.QuestionId == id);
        }

        public void Store(MathAnswerable a)
        {
            if (a.QuestionId > 0)
            {
                var target = Context.MathAnswerables.FirstOrDefault(x => x.QuestionId == a.QuestionId);
                if (target == null)
                    Add(a);
                Mapper.Map(a, target);
            }
            else
            {
                Add(a);
            }
        }

        public void Delete(int targetId, string userId)
        {
            var target = Context.MathAnswerables.FirstOrDefault(x => x.QuestionId == targetId);
            if (target == null)
                throw new ArgumentException("Not a valid id.");
            target.Delete(userId);
        }

        protected void Add(MathAnswerable a)
        {
            Context.MathAnswerables.Add(a);
        }

        public MathAnswerableRepository(ApplicationDbContext db)
            : base(db)
        {
        }
    }
}